//发行版本管理
const redisDao = require("./redisDao.js")
const mysqlDao = require("./mysqlDao.js")
const utils = require("./utils.js")
const uuid = require("uuid")
const oneDayTime = 86400000
var model = function() {}
//初始化
model.init = function() {
	this.editionMap = {}
	this.basicList = {}
	this.publishList = {}
	this.dayStr = ""
	redisDao.db.hgetall("edition",(err,data)=>{
		for(var name in data){
			this.editionMap[name] = JSON.parse(data[name])
			this.editionMap[name]["name"] = name
			this.timer = setInterval(this.update.bind(this),3000)
		}
	})
	redisDao.db.hgetall("basic",(err,data)=>{
		for(var name in data){
			this.basicList[name] = data[name]
		}
	})
	redisDao.db.hgetall("publish",(err,data)=>{
		for(var name in data){
			this.publishList[name] = data[name]
		}
	})}
model.update = function() {
	var curDayStr = (new Date()).toDateString()
	if(this.dayStr !== curDayStr){
		this.dayUpdate(curDayStr)
	}
}
//每日更新
model.dayUpdate = function(curDayStr) {
	console.log("每日更新")
	this.dayStr = curDayStr
	var list = this.getEditions()
	for(var name in list){
		if(list[name].sync == 1){
			this.editionInit(name)
		}
	}
}
//添加版本
model.addEdition = function(data,cb) {
	console.log("addEdition",data)
	if(!data.name || !data.post){
		cb(false,"参数错误")
		return
	}
	if(data.basic && !this.basicList[data.basic]){
		cb(false,"底层不存在")
		return
	}
	if(!this.editionMap[data.name]){
		//版本未存在
		this.editionMap[data.name] = {}
		this.editionMap[data.name].time = Date.now()
		this.editionMap[data.name].sync = 2
	}
	this.editionMap[data.name].name = data.name
	this.editionMap[data.name].rate = data.rate //分成比例
	this.editionMap[data.name].tip = data.tip 	//通道费
	this.editionMap[data.name].estimate = data.estimate //预估券比
	this.editionMap[data.name].des = data.des
	this.editionMap[data.name].post = data.post
	this.editionMap[data.name].url = data.url
	this.editionMap[data.name].publisher = data.publisher
	this.editionMap[data.name].basic = data.basic
	redisDao.db.hset("edition",data.name,JSON.stringify(this.editionMap[data.name]))
	cb(true,this.editionMap[data.name])
}
//删除版本
model.delEdition = function(name,cb) {
	if(!this.editionMap[name]){
		cb(false,"版本不存在")
		return
	}
	delete this.editionMap[name]
	redisDao.db.hdel("edition",name)
	redisDao.db.del("editionDay:"+name)
	redisDao.db.del("editionTotal:"+name)
	cb(true)
}
//停止更新
model.pauseSync = function(name,cb) {
	if(!this.editionMap[name]){
		cb(false,"版本不存在")
		return
	}
	this.editionMap[name].sync = 0
	redisDao.db.hset("edition",name,JSON.stringify(this.editionMap[name]))
	cb(true,this.editionMap[name])
}
//恢复更新
model.resumeSync = function(name,cb) {
	if(!this.editionMap[name]){
		cb(false,"版本不存在")
		return
	}
	if(this.editionMap[name].sync == 2)
		this.editionMap[name].time = Date.now()
	this.editionMap[name].sync = 1
	redisDao.db.hset("edition",name,JSON.stringify(this.editionMap[name]))
	this.editionMap[name].errorCount = 0
	cb(true,this.editionMap[name])
}
//获取数据并初始化
model.getDataAndEditionInit = function(name,cb) {
	this.editionMap[name].time = Date.now()
	redisDao.db.hset("edition",name,JSON.stringify(this.editionMap[name]))
	setTimeout(model.editionInit.bind(this,name),10000)
	cb(true)
}
//版本初始化
model.editionInit = function(name,cb) {
	redisDao.db.hgetall("editionDay:"+name,function(err,data) {
		var dayStr = (new Date()).toLocaleDateString()
		for(var i in data){
			data[i] = JSON.parse(data[i])
			if(i == dayStr){
				delete data[i]
			}
		}
		var monthMap = {}
		var weekMap = {}
		//月计算
		for(var i in data){
			var str = utils.getMonth(data[i]["date"])
			if(!monthMap[str]){
				monthMap[str] = {
					"date" : str,
					"accNum":0,
					"userNum":0,
					"activeNum":0,
					"n_pay_amount":0,
					"a_pay_amount":0,
					"n_pay_number":0,
					"a_pay_number":0,
					"n_pay_user":0,
					"a_pay_user":0
				}
			}
			monthMap[str]["accNum"] += data[i]["accNum"]
			monthMap[str]["userNum"] += data[i]["userNum"]
			monthMap[str]["activeNum"] += data[i]["activeNum"]
			monthMap[str]["n_pay_amount"] += data[i]["n_pay_amount"]
			monthMap[str]["a_pay_amount"] += data[i]["a_pay_amount"]
			monthMap[str]["n_pay_number"] += data[i]["n_pay_number"]
			monthMap[str]["a_pay_number"] += data[i]["a_pay_number"]
			monthMap[str]["n_pay_user"] += data[i]["n_pay_user"]
			monthMap[str]["a_pay_user"] += data[i]["a_pay_user"]
		}
		//周计算
		for(var i in data){
			var str = utils.getWeek(data[i]["date"])
			if(!weekMap[str]){
				weekMap[str] = {
					"date" : str,
					"accNum":0,
					"userNum":0,
					"activeNum":0,
					"n_pay_amount":0,
					"a_pay_amount":0,
					"n_pay_number":0,
					"a_pay_number":0,
					"n_pay_user":0,
					"a_pay_user":0
				}
			}
			weekMap[str]["accNum"] += data[i]["accNum"]
			weekMap[str]["userNum"] += data[i]["userNum"]
			weekMap[str]["activeNum"] += data[i]["activeNum"]
			weekMap[str]["n_pay_amount"] += data[i]["n_pay_amount"]
			weekMap[str]["a_pay_amount"] += data[i]["a_pay_amount"]
			weekMap[str]["n_pay_number"] += data[i]["n_pay_number"]
			weekMap[str]["a_pay_number"] += data[i]["a_pay_number"]
			weekMap[str]["n_pay_user"] += data[i]["n_pay_user"]
			weekMap[str]["a_pay_user"] += data[i]["a_pay_user"]
		}
		for(var i in weekMap)
			weekMap[i] = JSON.stringify(weekMap[i])
		for(var i in monthMap)
			monthMap[i] = JSON.stringify(monthMap[i])
		redisDao.db.hmset("editionWeek:"+name,weekMap)
		redisDao.db.hmset("editionMonth:"+name,monthMap)
		if(cb)
			cb(true)
	})
}
//获取版本
model.getEditions = function() {
	return this.editionMap
}
//获取底层
model.getBasic = function() {
	return this.basicList
}
//添加底层
model.addBasic = function(name,des,cb) {
	console.log("addBasic",name)
	if(!name || this.basicList[name]){
		cb(false,"参数错误或已存在该底层")
		return
	}
	this.basicList[name] = des
	redisDao.db.hset("basic",name,this.basicList[name])
	cb(true,{name:this.basicList[name]})
}
//删除底层
model.delBasic = function(name,cb) {
	console.log("addBasic",name)
	if(!this.basicList[name]){
		cb(false,"该底层不存在")
		return
	}
	delete this.basicList[name]
	redisDao.db.hdel("basic",name)
	cb(true)
}
//获取底层数据 名称  今日收益  本周收益  本月收益  总版本数  最后上线版本  活跃中数量 空档天数 
model.getBasicData = function(cb) {
	var self = this
	self.getRevenues(function(map) {
		var list = self.getEditions()
		var editionBasic = {}
		for(var i in list){
			if(list[i]["basic"]){
				if(!editionBasic[list[i]["basic"]])
					editionBasic[list[i]["basic"]] = []
				var info = Object.assign({name:i},list[i])
				info.day = 0
				info.week = 0
				info.month = 0
				info.b_month = 0
				info.all = 0
				if(map[i]){
					if(map[i][0])
						info.day = map[i][0].a_pay_amount
					if(map[i][1])
						info.week = map[i][1].a_pay_amount
					if(map[i][2])
						info.month = map[i][2].a_pay_amount
					if(map[i][3])
						info.b_month = map[i][3].a_pay_amount
					if(map[i][4])
						info.all = map[i][4]
				}
				editionBasic[list[i]["basic"]].push(info)
			}
		}
		var basicInfos = []
		for(var i in self.basicList){
			var info = {}
			info.id = i
			info.name = self.basicList[i]
			info.day = 0
			info.week = 0
			info.month = 0
			info.b_month = 0
			info.all = 0
			info.count = 0
			info.active = 0
			info.last = ""
			info.lastTime = -1
			if(editionBasic[i]){
				info.count = editionBasic[i].length
				for(var j = 0;j < editionBasic[i].length;j++){
					if(editionBasic[i][j]["sync"] == 1)
						info.active++
					if(editionBasic[i][j]["time"] > info.lastTime){
						info.last = editionBasic[i][j]["name"]
						info.lastTime = editionBasic[i][j]["time"]
					}
					info.day += editionBasic[i][j]["day"]
					info.week += editionBasic[i][j]["week"]
					info.month += editionBasic[i][j]["month"]
					info.b_month += editionBasic[i][j]["b_month"]
					info.all += editionBasic[i][j]["all"]
				}
			}
			basicInfos.push(info)
		}
		cb(basicInfos)
	})
}
//获取发行
model.getPublish = function() {
	return this.publishList
}
//添加发行
model.addPublish = function(name,des,cb) {
	console.log("addPublish",name)
	if(!name || this.publishList[name]){
		cb(false,"参数错误或已存在该发行")
		return
	}
	this.publishList[name] = des
	redisDao.db.hset("publish",name,this.publishList[name])
	cb(true,{name:this.publishList[name]})
}
//删除发行
model.delPublish = function(name,cb) {
	console.log("addPublish",name)
	if(!this.publishList[name]){
		cb(false,"该发行不存在")
		return
	}
	delete this.publishList[name]
	redisDao.db.hdel("publish",name)
	cb(true)
}
//获取发行数据 名称  今日收益  本周收益  本月收益  总版本数  最后上线版本  活跃中数量 空档天数 
model.getPublishData = function(cb) {
	var self = this
	self.getRevenues(function(map) {
		var list = self.getEditions()
		var editionPublish = {}
		for(var i in list){
			if(list[i]["publisher"]){
				if(!editionPublish[list[i]["publisher"]])
					editionPublish[list[i]["publisher"]] = []
				var info = Object.assign({name:i},list[i])
				info.day = 0
				info.week = 0
				info.month = 0
				info.b_month = 0
				info.all = 0
				if(map[i]){
					if(map[i][0])
						info.day = map[i][0].a_pay_amount
					if(map[i][1])
						info.week = map[i][1].a_pay_amount
					if(map[i][2])
						info.month = map[i][2].a_pay_amount
					if(map[i][3])
						info.b_month = map[i][3].a_pay_amount
					if(map[i][4])
						info.all = map[i][4]
				}
				editionPublish[list[i]["publisher"]].push(info)
			}
		}
		var publishInfos = []
		for(var i in self.publishList){
			var info = {}
			info.id = i
			info.name = self.publishList[i]
			info.day = 0
			info.week = 0
			info.month = 0
			info.b_month = 0
			info.all = 0
			info.count = 0
			info.active = 0
			info.last = ""
			info.lastTime = -1
			if(editionPublish[i]){
				info.count = editionPublish[i].length
				for(var j = 0;j < editionPublish[i].length;j++){
					if(editionPublish[i][j]["sync"] == 1)
						info.active++
					if(editionPublish[i][j]["time"] > info.lastTime){
						info.last = editionPublish[i][j]["name"]
						info.lastTime = editionPublish[i][j]["time"]
					}
					info.day += editionPublish[i][j]["day"]
					info.week += editionPublish[i][j]["week"]
					info.month += editionPublish[i][j]["month"]
					info.b_month += editionPublish[i][j]["b_month"]
					info.all += editionPublish[i][j]["all"]
				}
			}
			publishInfos.push(info)
		}
		cb(publishInfos)
	})
}
//获取全版本日月周收益
model.getRevenues = function(cb) {
	var infos = this.getEditions()
	var list = []
	var multiList = []
	var map = {}
	for(var i in infos){
		list.push({name : i})
		multiList.push(["hget","editionDay:"+i,(new Date(Date.now()-oneDayTime)).toLocaleDateString()])
		multiList.push(["hget","editionWeek:"+i,utils.getBeforeWeek(0)])
		multiList.push(["hget","editionMonth:"+i,utils.getBeforeMonth(0)])
		multiList.push(["hget","editionMonth:"+i,utils.getBeforeMonth(1)])
		multiList.push(["hget","editionTotal:"+i,"amount"])
	}
	redisDao.multi(multiList,function(err,data) {
		for(var i = 0;i < list.length;i++){
			var info = []
			for(var j = 0;j < 5;j++){
				var tmp = data.shift()
				if(tmp)
					info.push(JSON.parse(tmp))
				else
					info.push(null)
			}
			map[list[i]["name"]] = info
		}
		cb(map)
	})
}
//获取对账单总数量
model.getStatementPage = function(otps,cb) {
	mysqlDao.getStatementPage(otps,cb)
}
//获取对账单
model.getStatement = function(otps,cb) {
	mysqlDao.getStatement(otps,cb)
}
//添加对账单
model.addStatement = function(otps,cb) {
	if(!this.editionMap[otps.edition]){
		cb(false,"edition error "+otps.edition)
		return
	}
	mysqlDao.addStatement(otps,cb)
}
//确认回款
model.finishStatement = function(otps,cb) {
	mysqlDao.finishStatement(otps,cb)
}
//作废对账单
model.repealStatement = function(otps,cb) {
	mysqlDao.repealStatement(otps,cb)
}
//获取对账单统计数据
model.getStatementStat = function(otps,cb) {
	mysqlDao.getStatementStat(otps,cb)
}
module.exports = model